<?php
declare (strict_types=1);

namespace app\middleware;

use app\common\JwtUtil;
use Firebase\JWT\ExpiredException;
use think\Request;
use think\Response;

class CheckLogin {
	public function handle(Request $request, \Closure $next) {
		$url = $request->url();
		$url = strtolower($url);
//		preg_match_all("/\/(.*)\//",$url,$checkUrl);
		//第一个属性是正则条件，第二个属性为要匹配的字段，第三个属性为生成的结果数组
		preg_match("/\/(([a-z]|[A-Z])*)\//",$url,$checkUrl);
		if ('/reception/login' == $url) {
			return $next($request);
		}
		//获取前端放在报头传过来的token
		@$token = $_SERVER['HTTP_TOKEN'];
		if (empty($token)) {
			return Response::create(['error' => '尚未登录', 'status' => false], 'json', 403);
		}
		//通过session获取用户身份信息来判断访问权限
		$s=session('identity');
		if ($s == $checkUrl['1']) {
			try {
				JwtUtil::decode($token);
				return $next($request);
			} catch (ExpiredException $e) {
				return Response::create(['error' => '登录超时', 'status' => false], 'json', 403);
			} catch (\Exception $e) {
				return Response::create(['error' => '登录信息失效', 'status' => false], 'json', 403);
			}
		}elseif ($s == 'all'){
			return $next($request);
		}else{
			return Response::create(['error' => '无权限访问该网址', 'status' => false], 'json', 403);
		}
	}
}
